<?php

#doc
#	classname:	QNewsController
#	scope:		PUBLIC
#
#/doc

class QNewsController extends Controller {
    #	News Controller, this calss responsibility to edit news logic

	
	public function filters()
		{
			return array(
	              'accessControl',
			);
		}
	
		public function accessRules()
		{
			return array(
				array('allow',
	                'actions'=>array('add','list','edit','del','Categorylist','EditCategory','AddCategory','DelCategory'),
	                'roles'=>array('admin'),
			),
			
			array('deny',
	                'actions'=>array('add','list','edit','del','Categorylist','EditCategory','AddCategory','DelCategory'),
	                'users'=>array('*'),
			),
			);
		}
	
	
	
	
    public $layout = "application.views.layouts.admin";

    #	Function to add news
    public function actionAdd() {
       
         $news = new News();
        
       if (isset($_POST['ajax'])&& $_POST['ajax']==='news')
	            {
	                # code...
	                echo CActiveForm::validate($reguser);
	                Yii::app()->end();
	            }
        
        if (isset($_POST['News'])) 
        {
        	$news->attributes=$_POST['News'];
        	$news->image = CUploadedFile::getInstance($news,'image'); 
	        	$imgas=preg_split('/[.]+/',$news->image, -1, PREG_SPLIT_NO_EMPTY); 
				$imgas[0]=mktime(date("s"),date("Y"),date("m"),date("d"));			 
			
			
		
        	if ($news->validate('reg'))
			{
				 
				 $news->user_id = Yii::app()->user->id;
				 $news->id_tag=$_POST['taglist'];
				 $news->date=date('Y-m-d H:i:s');
				
				if ($news->image!="") {
					$news->image->saveAs('images/news/'.$imgas[0].".".$imgas[1]);
					$news->image=$imgas[0].".".$imgas[1];
				}
					
					
					
				 if($news->save())
				 {
				 	$this->Resize($news->image,125,125);
				 	$this->redirect('/admin/qnews/list/');
				 }
			}
        	
        }
        	 $tagi=Tag::model()->findAll();
               $list = CHtml::listData($tagi, 'id_tag', 'name_tag');
        $this->render("application.views.qnews.add",array('news'=>$news,'list'=>$list));
    }

	private function Delete($nameImg) 
		{
			if(@fopen('images/news/'.$nameImg, "r"))
			{
			 	$imga_del=preg_split('/[.]+/',$nameImg, -1, PREG_SPLIT_NO_EMPTY);
				 		unlink('images/news/'.$nameImg);
			}
				 		
		}
	private function Resize($nameImage,$with,$height) 
		{
			
			
			Yii::app()->setComponents(array('imagemod'=>array('class'=>'application.extensions.imagemodifier.CImageModifier')));
				 		
				 $imga = Yii::app()->imagemod->load('images/news/'.$nameImage);
				 $imga->image_resize          = true;
				$imga->image_y         = $height;
				$imga->image_x         = $with;
				//$imga->file_new_name_body = $img->file_src_name;
				$imga->process('images/news/');
				if ($imga->processed) {					
					$imga->clean();
					$imga=preg_split('/[.]+/',$nameImage, -1, PREG_SPLIT_NO_EMPTY); 				
					
					rename('images/news/'.$imga[0]."_1.".$imga[1],'images/news/'.$nameImage);
				} else {
					echo 'error : ' . $img->error;
			}
		}
    # View all news
    public function actionList() {
      	$page_size =5; 
        $news = News::model()->with('Coments','Tag')->recently(0,$page_size)->findAll();
        $news_count = News::model()->count();
          $count_page=$news_count/$page_size;
     	if(!isset($_GET['page']))
         {         	
         		$news=News::model()->with('Coments','Tag')->recently(0,$page_size)->findAll();                   
         }
         else
           {
           	$page=$_GET['page'];
             $sdvig = $page_size*($page-1);
             $news=News::model()->with('Coments','Tag')->recently( $sdvig,$page_size)->findAll();
           }
    	
    	
    	
        $this->render("application.views.qnews.list", array('news' => $news,'count_page'=>$count_page+1,));
    }

    # Delete current news
    public function actionDel() {
        $news_id = $_GET['id'];
   	 $inf_delete = News::model()->findByPk($news_id);
        if ($inf_delete->image!="") {
        	$this->Delete($inf_delete->image);
        }
        News::model()->deleteByPk($news_id);
        
        
        Coments::model()->deleteAll('id_post=:id_post AND object=:object',array(':id_post' => $news_id,':object'=>'news'));
        $this->redirect('/admin/qnews/list/');
    }

    #Update news new style
    public function actionEdit() {
        $news_id = $_GET['id'];
	//
	$news=News::model()->findByPk($news_id);
    if (isset($_POST['ajax'])&& $_POST['ajax']==='news')
	            {
	                # code...
	                echo CActiveForm::validate($reguser);
	                Yii::app()->end();
	            }
        
        if (isset($_POST['News'])) 
        {
        	
			 $news->attributes=$_POST['News'];			 
			 
        if ($news->validate('reg'))
			{
				 
				$img= CUploadedFile::getInstance($news,'image'); 
		
				if($img!=null)
				 	{
				 		$inf_delete = News::model()->findByPk($news_id);
				 		$this->Delete($inf_delete->image);
				 			$news->image=  CUploadedFile::getInstance($news,'image'); 		 
				 		
				 		  $imgas=preg_split('/[.]+/',$news->image, -1, PREG_SPLIT_NO_EMPTY); 
							 $imgas[0]=mktime(date("s"),date("Y"),date("m"),date("d"));	
				 		$news->image->saveAs('images/news/'.$imgas[0].".".$imgas[1]);
				 		$news->image=$imgas[0].".".$imgas[1];
				 		$this->Resize($news->image,125,125);
				 		
				 	}
				 $news->id_tag=$_POST['taglist'];
				 //$usercv->date=date();

				 if($news->save())
				 {
				 	$this->redirect('/admin/qnews/list/');
				 }
			}
        	
        }
       // $news = news::model()->findByPk($news_id);
        $tagi=Tag::model()->findAll();
        $New = new News();
        $list = CHtml::listData($tagi, 'id_tag', 'name_tag');
        $this->render("application.views.qnews.edit",array('news' => $news, 'New'=>$New,'list'=>$list));
    }

   #Далее идет работа с категориями
   
    #Список категорий
    public function actionCategorylist() 
    {
    	$page_size =5; 
        $tag = Tag::model()->recently(0,$page_size)->findAll();
        $tag_count = Tag::model()->count();
          $count_page=$tag_count/$page_size;
     	if(!isset($_GET['page']))
         {         	
         		$tag=Tag::model()->recently(0,$page_size)->findAll();                   
         }
         else
           {
           	$page=$_GET['page'];
             $sdvig = $page_size*($page-1);
             $tag=Tag::model()->recently( $sdvig,$page_size)->findAll();
           }
    	
    	
    	$this->render("application.views.qnews.categorylist",array('tag'=>$tag,'count_page'=>$count_page+1));
    }
    
    #Редактирование категорий
    
    public function actionEditCategory() 
    {
    	 $tag_id = $_GET['id'];
	//echo $tag_id;
	$tag=Tag::model()->findByPk($tag_id);
    if (isset($_POST['ajax'])&& $_POST['ajax']==='tag')
	            {
	                # code...
	                echo CActiveForm::validate($reguser);
	                Yii::app()->end();
	            }
        
        if (isset($_POST['Tag'])) 
        {
        	
			 $tag->attributes=$_POST['Tag'];			 
			 
        if ($tag->validate('reg'))
			{
				 
				// $usercv->user_id = Yii::app()->user->id;
				// $tag->id_tag=$_POST['taglist'];
				 //$usercv->date=date();

				 if($tag->save())
				 {
				 	$this->redirect('/admin/qnews/categorylist/');
				 }
			}
        	
        }
       // $news = news::model()->findByPk($news_id);
       
        $Tagi = new Tag();
       
        $this->render("application.views.qnews.editcategory",array('tag' => $tag, 'Tagi'=>$Tagi));
    }
    
    #Добавление новой категории
    public function actionAddCategory() 
    {
    	
    	 $tag = new Tag();
        
       if (isset($_POST['ajax'])&& $_POST['ajax']==='tag')
	            {
	                # code...
	                echo CActiveForm::validate($reguser);
	                Yii::app()->end();
	            }
        
        if (isset($_POST['Tag'])) 
        {
        	
			 $tag->attributes=$_POST['Tag'];			 
			//print_r($_POST['News']);
		
        if ($tag->validate('reg'))
			{
				 
			
					
				 if($tag->save())
				 {
				 	$this->redirect('/admin/qnews/categorylist/');
				 }
			}
        	
        }
        	
        $this->render("application.views.qnews.addcategory",array('tag'=>$tag));
    	
    }
    
    #Удаление категорий
 	public function actionDelCategory() {
        $tag_id = $_GET['id'];
        Tag::model()->deleteByPk($tag_id);       
        $this->redirect('/admin/qnews/categorylist/');
    }

}

?>
